'use strict';

const RouterService = require('../base');

class DailyMenuItemService extends RouterService {
  static get modelName() {
    return 'Business.DailyMenuItem';
  }

  getListInclude(){
    return [
      {
        model: this.ctx.model.Business.Dish,
        as: 'dish',
        attributes: ['id', 'name', 'category', 'unit']
      }
    ]
  }
    // 批量创建菜单项
  async batchCreate(menuItems) {
    const { ctx } = this;

    // 验证数据
    if (!Array.isArray(menuItems) || menuItems.length === 0) {
      throw new Error('菜单项数据不能为空');
    }

    // 验证必要字段
    for (const item of menuItems) {
      if (!item.daily_menu_id || !item.dish_id || !item.planned_quantity) {
        throw new Error('菜单项数据不完整，缺少必要字段');
      }
    }

    // 检查是否已存在相同的菜品
    const dailyMenuId = menuItems[0].daily_menu_id;
    const dishIds = menuItems.map(item => item.dish_id);

    const existingItems = await this.model.findAll({
      where: {
        daily_menu_id: dailyMenuId,
        dish_id: dishIds,
        deleted: 0
      },
      include: [
        {
          model: ctx.model.Business.Dish,
          as: 'dish',
          attributes: ['id', 'name', 'category', 'unit']
        }
      ]
    });

    if (existingItems.length > 0) {
      const existingDishIds = existingItems.map(item => item.dish.name);
      throw new Error(`以下菜品已存在于该采购单中: ${existingDishIds.join(', ')}`);
    }

    // 批量创建
    const result = await this.model.bulkCreate(menuItems);

    return result;
  }

  // 批量更新菜单项
  async batchUpdate(menuItems) {
    const { ctx } = this;

    // 验证数据
    if (!Array.isArray(menuItems) || menuItems.length === 0) {
      return {success: true, updatedCount: 0}
    }
    for (let i = 0; i < menuItems.length; i++) {
      const element = menuItems[i];
      if (element.planned_quantity === 0) {
        await this.model.destroy({
          where: { id: element.id, deleted: 0 }
        })
      } else {
        await this.model.update({
          ...element
        }, {
          where: { id: element.id, deleted: 0 }
        });
      }
    }
    return {success: true, updatedCount: menuItems.length}
  }



  // 获取菜单项列表，包含菜品信息
  async getMenuItems(dailyMenuId) {
    const { ctx } = this;

    const result = await this.model.findAll({
      where: {
        daily_menu_id: dailyMenuId,
        deleted: 0
      },
      include: [
        {
          model: ctx.model.Business.Dish,
          as: 'dish',
          attributes: ['id', 'name', 'category', 'unit']
        }
      ],
      order: [['create_time', 'ASC']]
    });

    return result;
  }

  async batchConfirmReceipt(menuItems) {
    if (!Array.isArray(menuItems) || menuItems.length === 0) {
      throw new Error('菜单项数据不能为空');
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      // 更细采购单的状态
      await this.ctx.model.Business.DailyMenu.update({
        status: 3
      }, {
        where: { id: menuItems[0].daily_menu_id, deleted: 0 },
        transaction
      });
      for (let i = 0; i < menuItems.length; i++) {
        const element = menuItems[i];
        await this.model.update({
          status: 3,
          actual_quantity2: element.actual_quantity2,
          quality_rating: element.quality_rating,
          remark: element.remark
        }, {
          where: { id: element.id, deleted: 0 },
          transaction
        });
      }
      await transaction.commit();
      return true;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
  async batchConfirmBuy(menuItems) {
    if (!Array.isArray(menuItems) || menuItems.length === 0) {
      throw new Error('菜单项数据不能为空');
    }
    // 创建事务
    const transaction = await this.ctx.model.transaction();
    try {
      // 更细采购单的状态
      await this.ctx.model.Business.DailyMenu.update({
        status: 2
      }, {
        where: { id: menuItems[0].daily_menu_id, deleted: 0 },
        transaction
      });
      for (let i = 0; i < menuItems.length; i++) {
        const element = menuItems[i];
        await this.model.update({
          status: 2,
          actual_quantity: element.actual_quantity,
          actual_price: element.actual_price
        }, {
          where: { id: element.id, deleted: 0 },
          transaction
        });
      }
      await transaction.commit();
      return true;
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }
}

module.exports = DailyMenuItemService;
